import { inject, onUnmounted } from "vue";

export interface ToggleItemCustomHooks {
  onShow: (fn: () => void) => void;
  onShowOnce: (fn: () => void) => void;
  removeShowHandler: (fn: () => void) => void;
  onHide: (fn: () => void) => void;
  onHideOnce: (fn: () => void) => void;
  removeHideHandler: (fn: () => void) => void;
}

export function useToggleItemId(): string {
  return inject("toggle-item-id") as string;
}

/**
 * 所在toggle-view-item中显示时执行钩子
 * @param fn
 */
export function useOnShow(fn: () => void) {
  const util = inject<ToggleItemCustomHooks>("toggle-item-custom-hooks");
  if (util == null) {
    throw new Error("toggle-item-custom-hooks is not defined");
  }
  util.onShow(fn);
  onUnmounted(() => util.removeShowHandler(fn));
}

/**
 * 所在toggle-view-item中显示时执行钩子,只执行一次
 * @param fn
 */
export function useOnShowOnce(fn: () => void) {
  const util = inject<ToggleItemCustomHooks>("toggle-item-custom-hooks");
  if (util == null) {
    throw new Error("toggle-item-custom-hooks is not defined");
  }
  util.onShowOnce(fn);
  onUnmounted(() => util.removeShowHandler(fn));
}

/**
 * 所在toggle-view-item中隐藏时执行钩子
 * @param fn
 */
export function useOnHide(fn: () => void) {
  const util = inject<ToggleItemCustomHooks>("toggle-item-custom-hooks");
  if (util == null) {
    throw new Error("toggle-item-custom-hooks is not defined");
  }
  util.onHide(fn);
  onUnmounted(() => util.removeShowHandler(fn));
}

/**
 * 所在toggle-view-item中隐藏时执行钩子,只执行一次
 * @param fn
 */
export function useOnHideOnce(fn: () => void) {
  const util = inject<ToggleItemCustomHooks>("toggle-item-custom-hooks");
  if (util == null) {
    throw new Error("toggle-item-custom-hooks is not defined");
  }
  util.onHideOnce(fn);
  onUnmounted(() => util.removeShowHandler(fn));
}

export interface ToggleViewContext {
  switchView: (key: string) => void;
}

export interface ToggleViewRef extends ToggleViewContext {}

/**
 * 获取toggle-view上下文
 */
export function useToggleViewContext() {
  return inject<ToggleViewContext>("toggle-view:ctx", () => null as any, true);
}
